package com.wp.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wp.admin.mapper.SysUserMapper;
import com.wp.admin.pojo.SysDept;
import com.wp.admin.pojo.SysMenu;
import com.wp.admin.pojo.SysUser;
import com.wp.admin.service.SysDeptService;
import com.wp.admin.service.SysMenuService;
import com.wp.admin.service.SysUserService;
import com.wp.common.enums.ExceptionEnum;
import com.wp.common.exception.ScException;
import com.wp.common.vo.PageRequest;
import com.wp.common.vo.PageResult;
import com.wp.model.admin.input.dto.SaveUserInputDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wp
 * @create 2019-03-03 15:48
 */
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public SysUser findByUserName(String userName) {
        SysUser user = new SysUser();
        user.setUserName(userName);
        user = sysUserMapper.selectOne(user);
        return user;
    }

    @Override
    public Set<String> findPermissionsByUserName(String userName) {
        List<SysMenu> sysMenus = sysMenuService.findByUserName(userName);
        return sysMenus.stream().filter(menu -> StringUtils.isNotBlank(menu.getPerms())).collect(Collectors.toList()).stream().map(SysMenu::getPerms).collect(Collectors.toSet());
    }

    @Override
    public SysUser findUserById(Long userId) {
        if (userId != null) {
            return sysUserMapper.selectByPrimaryKey(userId);
        }
        return null;
    }

    @Override
    public PageResult<SysUser> findPage(PageRequest pageRequest) {
        // 开启分页
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        // 过滤条件
        Example example = new Example(SysUser.class);
        if (StringUtils.isNotBlank(pageRequest.getKey())) {
            example.createCriteria().orLike("userName", "%" + pageRequest.getKey() + "%");
        }
        if (StringUtils.isNotBlank(pageRequest.getSortBy())) {
            String sortByClause = pageRequest.getSortBy() + (pageRequest.getDesc() ? " DESC" : " ASC");
        }
        List<SysUser> userList = sysUserMapper.selectByExample(example);
        // 查询机构名称
        List<Long> deptIds = userList.stream().map(SysUser::getDeptId).collect(Collectors.toList());
        List<SysDept> sysDeptList = sysDeptService.findDeptByIds(deptIds);
        // 把sysDeptList变成一个map，key是id，值是名称
        Map<Long, String> deptMap = sysDeptList.stream().collect(Collectors.toMap(SysDept::getId, SysDept::getName));
        // 设置机构名称
        userList.forEach(user -> user.setDeptName(deptMap.get(user.getDeptId())));
        if (CollectionUtils.isEmpty(userList)) {
            throw new ScException(ExceptionEnum.USER_NOT_FOUND);
        }
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return new PageResult<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages(), userList);
    }

    @Override
    public void saveUser(SaveUserInputDTO saveUserInputDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(saveUserInputDTO, sysUser);
        sysUser.setId(null);
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(true);
        sysUser.setDelFlag(false);
        sysUserMapper.insert(sysUser);
    }

}
